package com.nbpt.edu.commercesites.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbpt.edu.commercesites.mapper.CategoryMapper;
import com.nbpt.edu.commercesites.mapper.GoodMapper;
import com.nbpt.edu.commercesites.mapper.GoodTypeMapperMapper;
import com.nbpt.edu.commercesites.mapper.TypeMapper;
import com.nbpt.edu.commercesites.service.GoodService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pojo.*;
import pojo.entity.GoodEntity;
import pojo.vo.GoodVo;
import pojo.vo.GoodVo2;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodServiceImpl extends ServiceImpl<GoodMapper, Good> implements GoodService {
    @Autowired
    GoodMapper goodMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    TypeMapper typeMapper;
    @Autowired
    GoodTypeMapperMapper goodTypeMapperMapper;

//单属性查询
    @Transactional
    @Override
    public List<Good> getGoodList() {
        return goodMapper.selectList(null);
    }
//多表连接
    @Transactional
    @Override
    public List<GoodVo> getGoodListMatch() {
        List<Good> goods = goodMapper.selectList(null);
        List<GoodVo> goodVos=new ArrayList<>();
        for (int i = 0; i < goods.size(); i++) {
            GoodVo goodVo=new GoodVo();
            List<Type> types=new ArrayList<>();
            BeanUtils.copyProperties(goods.get(i),goodVo);
            goodVo.setCategory(categoryMapper.selectById(goods.get(i).getgCategoryId()));
            QueryWrapper queryWrapper=new QueryWrapper();
           queryWrapper.eq("g_id",goodVo.getId());
            List<GoodTypeMapping> list = goodTypeMapperMapper.selectList(queryWrapper);
            List<Type> typelist=new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                Type type = typeMapper.selectById(list.get(j).gettId());
                typelist.add(type);
            }
            goodVo.setTypes(typelist);
            goodVos.add(goodVo);
        }
        return goodVos;
    }
    @Transactional
    @Override
    public GoodVo getGoodMatchById(Long id) {
        Good good = goodMapper.selectGoodById(id);
        GoodVo goodVo=new GoodVo();
        if(good!=null) {
            BeanUtils.copyProperties(good, goodVo);
        }
        goodVo.setCategory(categoryMapper.selectById(goodVo.getgCategoryId()));
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("g_id",goodVo.getId());

        List<GoodTypeMapping> list = goodTypeMapperMapper.selectList(queryWrapper);
        List<Type> types=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            types.add(typeMapper.selectById(list.get(i).gettId()));
        }
        goodVo.setTypes(types);
        return goodVo;
    }
    @Override
    public List<Good> getGoodHot() {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("g_hot",true);
        goodMapper.selectList(queryWrapper);
        return goodMapper.selectList(queryWrapper);
    }

    @Override
    public List<Good> getGoodNotHot() {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.ne("g_hot",true);
        goodMapper.selectList(queryWrapper);
        return goodMapper.selectList(queryWrapper);
    }

    @Override
    public Good getGoodById(Long id) {
        return goodMapper.selectGoodById(id);
    }
    @Transactional
    @Override
    public Page<Good> getGoodListPage(Integer current, Integer size, String gName, Long gCategoryId, Boolean gHot) {
        IPage iPage=new Page();
        iPage.setCurrent(current)
                .setSize(size);
        Page<Good> page=new Page(current,size);
        page.addOrder(OrderItem.asc("id"));
    QueryWrapper<Good> queryWrapper = new QueryWrapper<>();

    if (StringUtils.isNotBlank(gName)) {
        queryWrapper.eq("g_name", gName); // 商品名称模糊匹配
    }

    if (gCategoryId != null && gCategoryId > 0) {
        queryWrapper.eq("g_category_id", gCategoryId); // 分类 ID 精确匹配
    }

    if (gHot != null) {
        queryWrapper.eq("g_hot", gHot); // 是否热销精确匹配
    }

    // 固定条件：只查未删除的商品（软删除标志）
    queryWrapper.eq("g_delflag", false);


    return goodMapper.selectPage(page,queryWrapper);
    }
    @Override
    public List<Type> getType() {
        typeMapper.selectList(null);
        return typeMapper.selectList(null);
    }

    @Override
    public List<Category> getCategory() {
    return categoryMapper.selectList(null);
    }

    @Transactional
    public Boolean insertGood(GoodEntity goodEntity) {
        // 1. 插入或更新商品信息
        Good good = new Good();
        BeanUtils.copyProperties(goodEntity, good);

        int result;
        Long gId = good.getId();

        if (gId == null || goodMapper.selectById(gId) == null) {

            result = goodMapper.insert(good);
            if (result <= 0) {
                throw new RuntimeException("商品插入失败");
            }
            gId = good.getId();
        } else {
            result = goodMapper.updateById(good);
            if (result <= 0) {
                throw new RuntimeException("商品更新失败");
            }
        }

        if (gId == null) {
            throw new RuntimeException("获取商品ID失败");
        }
        QueryWrapper<GoodTypeMapping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("g_id", gId);
        goodTypeMapperMapper.delete(queryWrapper);
        for (String typeName : goodEntity.getTypenames()) {
            Type type = typeMapper.selectOne(new QueryWrapper<Type>().eq("t_name", typeName));
            if (type == null) {
                throw new RuntimeException("找不到类型: " + typeName);
            }

            GoodTypeMapping mapping = new GoodTypeMapping();
            mapping.setgId(gId);
            mapping.settId(type.gettId());

            goodTypeMapperMapper.insert(mapping);
        }

        return true;
    }
    @Transactional
    @Override
    public Boolean insertCategory(Category category) {
        category.setcDelflag(false);
        category.setcStatus(false);
        int Result=categoryMapper.insert(category);
        return Result>0;
    }
    @Transactional
    @Override
    public Boolean insertType(Type type) {
        type.settDelflag(false);
        type.settStatus(false);
        int Result=typeMapper.insert(type);
        return Result>0;
    }



    @Override
    public Boolean deleteById(List<Long> ids) {
        return (goodMapper.deleteByIds(ids)>0);
    }

    @Override
    public Boolean deleteCategoryById(List<Long> ids) {
        return (categoryMapper.deleteByIds(ids)>0);
    }

    @Override
    public Boolean deleteTypeById(List<Long> ids) {
        return (typeMapper.deleteByIds(ids)>0);
    }

    @Transactional
    @Override
    public Boolean updateGood(GoodVo2 goodVO) {
    Good good=new Good();
    BeanUtils.copyProperties(goodVO,good);
    QueryWrapper queryWrapper=new QueryWrapper();
    queryWrapper.eq("id",goodVO.getId());
    goodMapper.update(goodVO,queryWrapper);
    goodTypeMapperMapper.deleteByGoodIdPhysical(goodVO.getId());
    for(String type:goodVO.getTypeName()){
        LambdaQueryWrapper<Type> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Type::gettName,type);
        GoodTypeMapping goodTypeMapping=new GoodTypeMapping();
        goodTypeMapping.settId(typeMapper.selectOne(lambdaQueryWrapper).gettId());
        goodTypeMapping.setgId(goodVO.getId());
        goodTypeMapperMapper.insert(goodTypeMapping);
    }
    return goodMapper.update(goodVO,queryWrapper)>0;
    }
    @Transactional
    @Override
    public Boolean updateCategory(Category category) {
    LambdaQueryWrapper<Category> lambdaQueryWrapper=new LambdaQueryWrapper();
    lambdaQueryWrapper.eq(Category::getcId,category.getcId());

        return (categoryMapper.update(category,lambdaQueryWrapper)>0);
    }

    @Override
    public List<Good> getGoodByCategory(String cName) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("c_name",cName);
        Category category = categoryMapper.selectOne(queryWrapper);
        LambdaQueryWrapper<Good> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Good::getgCategoryId,category.getcId());
        goodMapper.selectList(lambdaQueryWrapper);

        return goodMapper.selectList(lambdaQueryWrapper);
    }



    @Transactional
    @Override
    public List<String> getTypeById(Long id) {
    LambdaQueryWrapper<GoodTypeMapping> lambdaQueryWrapper=new LambdaQueryWrapper();
    lambdaQueryWrapper.eq(GoodTypeMapping::getgId,id);
        List<GoodTypeMapping> goodTypeMappings = goodTypeMapperMapper.selectList(lambdaQueryWrapper);
        List<String> types=new ArrayList<>();
        for (GoodTypeMapping goodTypeMapping:goodTypeMappings
             ) {
            LambdaQueryWrapper<Type> lambdaQueryWrapper1=new LambdaQueryWrapper();
            lambdaQueryWrapper1.eq(Type::gettId,goodTypeMapping.gettId());
            String type = typeMapper.selectOne(lambdaQueryWrapper1).gettName();
            types.add(type);
        }
        return types;
    }
    @Transactional
    @Override
    public IPage<Category> getCategoryPage(Integer current, Integer size) {
        Page<Category> page=new Page(current,size);
        page.addOrder(OrderItem.asc("c_id"));
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_delflag", false);
        return categoryMapper.selectCategoryPage(page,queryWrapper);
    }



}
